package com.pulsar.service.impl;

import com.pulsar.dao.AreaDao;
import com.pulsar.entity.Area;
import com.pulsar.handler.GlobalException;
import com.pulsar.message.ResponseCode;
import com.pulsar.service.AreaService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 功能描述: <br>
 * 所属包名: com.pulsar.service.impl<br>
 * 创建人　: 白剑<br>
 * 创建时间: 07/15/2018 16:47 Sunday<br>
 * 当前版本: 1.0<br>
 * 修改历史: <br>
 * 修改时间　　　　　修改人　　　　　版本变更　　　　　修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@Service
public class AreaServiceImpl implements AreaService {

    @Autowired
    private AreaDao areaDao;

    @Override
    public List<Area> getAreaList() {
        return areaDao.queryArea();
    }

    @Override
    public Area getAreaById(Integer areaId) {
        return areaDao.queryAreaById(areaId);
    }

    @Transactional(rollbackFor = RuntimeException.class) // 默认就是RuntimeException
    @Override
    public boolean addArea(Area area) {
        if (StringUtils.isBlank(area.getAreaName())) {
            throw new GlobalException(ResponseCode.AREA_NAME_EMPTY);
        }

        area.setCreateTime(new Date());
        area.setLastEditTime(new Date());

        try {
            int rowNo = areaDao.insertArea(area);
            if (rowNo > 0) {
                return true;
            } else {
                throw new GlobalException(ResponseCode.AREA_INSERT_ERROR);
            }
        } catch (Exception e) {
            throw new GlobalException(ResponseCode.AREA_INSERT_ERROR);
        }
    }

    @Transactional
    @Override
    public boolean updArea(Area area) {
        if (area.getAreaId() == null) {
            throw new GlobalException(ResponseCode.AREA_ID_EMPTY);
        }

        area.setLastEditTime(new Date());

        try {
            int rowNo = areaDao.updateArea(area);
            if (rowNo > 0) {
                return true;
            } else {
                throw new GlobalException(ResponseCode.AREA_UPDATE_ERROR);
            }
        } catch (Exception e) {
            throw new GlobalException(ResponseCode.AREA_UPDATE_ERROR);
        }
    }

    @Override
    public boolean delArea(Integer areaId) {
        try {
            int rowNo = areaDao.deleteArea(areaId);
            if (rowNo > 0) {
                return true;
            } else {
                throw new GlobalException(ResponseCode.AREA_DELETE_ERROR);
            }
        } catch (Exception e) {
            throw new GlobalException(ResponseCode.AREA_DELETE_ERROR);
        }
    }
}
